package org.jeecg.modules.myteam.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.chanp.entity.KuybChanp;
import org.jeecg.modules.chanp.service.IKuybChanpService;
import org.jeecg.modules.myteam.entity.KuybTeam;
import org.jeecg.modules.myteam.service.IKuybTeamService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.order.entity.KuybOrder;
import org.jeecg.modules.order.entity.KuybOrderPolicy;
import org.jeecg.modules.order.service.IKuybOrderPolicyService;
import org.jeecg.modules.order.service.IKuybOrderService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 我的团队
 * @Author: jeecg-boot
 * @Date: 2021-10-09
 * @Version: V1.0
 */
@Api(tags = "我的团队")
@RestController
@RequestMapping("/myteam/kuybTeam")
@Slf4j
public class KuybTeamController extends JeecgController<KuybTeam, IKuybTeamService> {
    @Autowired
    private IKuybTeamService kuybTeamService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    IKuybOrderPolicyService kuybOrderPolicyService;

    @Autowired
    IKuybChanpService kuybChanpService;

    @Autowired
    IKuybOrderService kuybOrderService;

    @GetMapping(value = "/getPolicyListByOpenId")
    public Result<?> getPolicyListByOpenId(String openId) {
        List<KuybOrderPolicy> result = new ArrayList<>();

        // 找到他的所有下级
        List<KuybTeam> list = kuybTeamService.list(new LambdaQueryWrapper<KuybTeam>()
                .eq(KuybTeam::getParentopenid, openId)
                .orderByDesc(KuybTeam::getCreateTime)
                .last("limit 1, 20"));

        list.forEach(item -> {
            List<KuybOrderPolicy> list2 = kuybOrderPolicyService.list(new LambdaQueryWrapper<KuybOrderPolicy>().eq(KuybOrderPolicy::getOpenId, item.getOpenid()));
            list2.forEach(item2 -> {
                KuybChanp kuybChanp = kuybChanpService.getById(item2.getProductId());
                if(kuybChanp != null)
                    item2.setChanpMc(kuybChanp.getChanpmc());

                KuybOrder kuybOrder = kuybOrderService.getById(item2.getZhubid());
                if(kuybOrder != null)
                    item2.setDingdje(kuybOrder.getDingdje());

            });

            result.addAll(list2);
        });

        return Result.OK(result);
    }

    @GetMapping(value = "/bloodRelationship")
    public Result<?> bloodRelationship(Integer type, String shareBy, String myOpenId) {
		KuybTeam kuybTeam = kuybTeamService.getOne(new LambdaQueryWrapper<KuybTeam>()
				.eq(KuybTeam::getParentopenid, shareBy)
				.eq(KuybTeam::getOpenid, myOpenId), false);
		if(kuybTeam != null)
			return Result.error("已经关联过了");

		// 手机号查openid
		if(type.equals(1)) {
		    SysUser sysUser = sysUserService.getUserByPhone(shareBy);
		    if(sysUser != null)
                shareBy = sysUser.getOpenId();
        }

        kuybTeam = new KuybTeam();
        kuybTeam.setOpenid(myOpenId);
        kuybTeam.setParentopenid(shareBy);

        kuybTeamService.save(kuybTeam);

        return Result.OK();
    }

    /**
     * 分页列表查询
     *
     * @param kuybTeam
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "我的团队-分页列表查询")
    @ApiOperation(value = "我的团队-分页列表查询", notes = "我的团队-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(KuybTeam kuybTeam,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<KuybTeam> queryWrapper = QueryGenerator.initQueryWrapper(kuybTeam, req.getParameterMap());
        Page<KuybTeam> page = new Page<KuybTeam>(pageNo, pageSize);
        IPage<KuybTeam> pageList = kuybTeamService.page(page, queryWrapper);

        pageList.getRecords().forEach(item -> {
            SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getOpenId, item.getOpenid()), false);
            if (sysUser != null) {
                item.setUsername(sysUser.getRealname() == null ? "未获取" : sysUser.getRealname());
                item.setAvatar(sysUser.getAvatar());
                item.setChuds(statisticsChudsj(1, sysUser.getOpenId()));
                item.setChudje(statisticsChudsj(2, sysUser.getOpenId()));
                item.setMobile(sysUser.getPhone());
                item.setOpenid(sysUser.getOpenId());
            }
        });

        return Result.OK(pageList);
    }

    private Integer statisticsChudsj(int type, String openId) {
        AtomicInteger dingdje_hej = new AtomicInteger();
        AtomicInteger dingdsl_hej = new AtomicInteger();

        // 找到他的所有下级
        List<KuybTeam> list = kuybTeamService.list(new LambdaQueryWrapper<KuybTeam>().eq(KuybTeam::getParentopenid, openId));
        list.forEach(item -> {
            List<KuybOrder> list2 = kuybOrderService.list(new LambdaQueryWrapper<KuybOrder>().eq(KuybOrder::getDingdzt, 1).eq(KuybOrder::getOpenId, openId));
            list2.forEach(item2 -> {
                dingdje_hej.addAndGet(item2.getDingdje());
                dingdsl_hej.getAndIncrement();
            });
        });

        if(type == 1)
            return dingdsl_hej.get();

        if(type == 2)
            return dingdje_hej.get();

        return 0;
    }

    /**
     * 添加
     *
     * @param kuybTeam
     * @return
     */
    @AutoLog(value = "我的团队-添加")
    @ApiOperation(value = "我的团队-添加", notes = "我的团队-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody KuybTeam kuybTeam) {
        kuybTeamService.save(kuybTeam);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param kuybTeam
     * @return
     */
    @AutoLog(value = "我的团队-编辑")
    @ApiOperation(value = "我的团队-编辑", notes = "我的团队-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody KuybTeam kuybTeam) {
        kuybTeamService.updateById(kuybTeam);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "我的团队-通过id删除")
    @ApiOperation(value = "我的团队-通过id删除", notes = "我的团队-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        kuybTeamService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "我的团队-批量删除")
    @ApiOperation(value = "我的团队-批量删除", notes = "我的团队-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.kuybTeamService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "我的团队-通过id查询")
    @ApiOperation(value = "我的团队-通过id查询", notes = "我的团队-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        KuybTeam kuybTeam = kuybTeamService.getById(id);
        if (kuybTeam == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(kuybTeam);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param kuybTeam
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, KuybTeam kuybTeam) {
        return super.exportXls(request, kuybTeam, KuybTeam.class, "我的团队");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, KuybTeam.class);
    }

}
